package com.matriq.cloudmanager.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.ContactDetailActivity;
import com.matriq.cloudmanager.entity.ClassContacts;
import com.matriq.cloudmanager.service.AccountService;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.EditText;
import android.widget.TextView;
import net.lgpage.fragment.BaseFragment;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Checker.StringUtils;
import net.lgpage.util.ChineseSpelling;
import net.lgpage.util.Cleaner;
import net.lgpage.util.Filter.ListFilter;
import net.lgpage.view.TextTouchView.OnItemTouchedListener;

public class ContactFragment extends BaseFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fm_contact, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setViews();
		setEvents();
		loadData();
	}

	android.support.v4.widget.SwipeRefreshLayout srl;
	android.support.v7.widget.RecyclerView rcy_contact;
	net.lgpage.view.TextTouchView ttv;
	EditText et_search;
	TextView tv_index;

	LinearLayoutManager adp_mng;

	private void setViews() {
		srl = (android.support.v4.widget.SwipeRefreshLayout) getView().findViewById(R.id.srl);
		rcy_contact = (android.support.v7.widget.RecyclerView) getView().findViewById(R.id.rcy_contact);
		rcy_adp = new RcyAdp();
		adp_mng = new LinearLayoutManager(getActivity());
		rcy_contact.setLayoutManager(adp_mng);
		rcy_contact.setAdapter(rcy_adp);
		ttv = (net.lgpage.view.TextTouchView) getView().findViewById(R.id.ttv);
		et_search = (EditText) getView().findViewById(R.id.et_search);
		tv_index = (TextView) getView().findViewById(R.id.tv_index);
	}

	private void setEvents() {
		et_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				filter();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		ttv.setListener(new OnItemTouchedListener() {

			@Override
			public void onItemTouch(int position, int action) {
				if (action == MotionEvent.ACTION_UP) {
					tv_index.setVisibility(View.INVISIBLE);
				} else {

					tv_index.setText(datas[position]);
					tv_index.setVisibility(View.VISIBLE);
					try {
						adp_mng.scrollToPositionWithOffset(data_index[position], 0);

					} catch (Exception e) {
					}
				}

			}
		});
		srl.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
	}

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		TextView tv_phone;
		TextView tv_name;
		TextView tv_catlog;

		public RcyViewHolder(View view) {
			super(view);
		}
	}

	RcyAdp rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}

		@Override
		public void onBindViewHolder(RcyViewHolder h, final int position) {
			final ClassContacts obj = rcylist.get(position);
			h.tv_phone.setText(obj.getPhone());
			h.tv_name.setText(obj.getName());
			if (indexs.contains(position)) {
				h.tv_catlog.setText(ChineseSpelling.getInstance().getSellingHead(obj.getName()).substring(0, 1));
				h.tv_catlog.setVisibility(View.VISIBLE);
			} else {
				h.tv_catlog.setVisibility(View.GONE);
			}
			h.itemView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					toActivity(ContactDetailActivity.class, obj);
				}
			});
		}

		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getActivity().getLayoutInflater().inflate(R.layout.rcy_contact, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.tv_phone = (TextView) cv.findViewById(R.id.tv_phone);
			h.tv_name = (TextView) cv.findViewById(R.id.tv_name);
			h.tv_catlog = (TextView) cv.findViewById(R.id.tv_catlog);
			return h;
		}
	}

	List<ClassContacts> rcylist;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(getActivity());
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<List<ClassContacts>> {

		public RcyListTask(Context context) {
			super(context);
		}

		@Override
		public List<ClassContacts> doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().class_list();
		}

		@Override
		public void onPostExecuteX(List<ClassContacts> result) {
			if (result == null) {
				return;
			} else {
				baselist = result;
				filter();
			}
		}
	}

	ListFilter<String, ClassContacts> filter = new ListFilter<String, ClassContacts>() {

		@Override
		public boolean accpet(String t, ClassContacts obj) {
			if (StringUtils.isEmpty(t))
				return true;
			String name = obj.getName();
			if (name.startsWith(t))
				return true;
			String head_name = ChineseSpelling.getInstance().getSellingHead(name);
			if (head_name.startsWith(t.toUpperCase()))
				return true;
			String tel = obj.getPhone();
			if (tel.startsWith(t))
				return true;
			return false;
		}
	};
	List<ClassContacts> baselist;

	private void filter() {
		String et_str = et_search.getEditableText().toString();
		rcylist = filter.doFilter(et_str, baselist);
		sort();
	}

	Map<String, List<ClassContacts>> all_map;

	List<Integer> indexs;

	private void sort() {
		all_map = new HashMap<>();
		if(rcylist==null)rcylist = new ArrayList<>();
		for (int i = 0; i < rcylist.size(); i++) {
			ClassContacts obj = rcylist.get(i);
			String key;
			try {
				key = ChineseSpelling.getInstance().getSellingHead(obj.getName()).subSequence(0, 1).toString()
						.toUpperCase();
				List<ClassContacts> value = all_map.get(key);
				if (value == null) {
					value = new ArrayList<ClassContacts>();
					all_map.put(key, value);
				}
				value.add(obj);
			} catch (Exception e) {
			}
		}
		rcylist.clear();
		indexs = new ArrayList<>();
		for (int i = 0; i < datas.length; i++) {
			List<ClassContacts> list = all_map.get(datas[i]);
			data_index[i] = rcylist.size();
			if (list != null && list.size() > 0) {
				indexs.add(rcylist.size());
				for (int j = 0; j < list.size(); j++) {
					rcylist.add(list.get(j));
				}
			}
		}
		rcy_adp.notifyDataSetChanged();
	}

	String[] datas = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
			"T", "U", "V", "W", "X", "Y", "Z" };
	int data_index[] = new int[datas.length];

	private void loadData() {
		refeshRcyList();
	}

	@Override
	public void onDestroy() {
		Cleaner.cleanTask(rcylistTask);
		super.onDestroy();
	}

}